$(function() {
	// 初始化权限
	var formPage = $('.suredy-form.readonly');
	if (formPage.length > 0) {
		$('.edit-data', formPage).remove();
		$('.show-data.editable', formPage).removeClass('show-data editable');
		$('.payed-status', formPage).removeClass('payed-status').attr('disabled', true);
	}

	// 初始化日期选择控件
	$.suredy.datetimepicker.init();

	// 创建子合同
	$('.children-contract-info').on('click', '.create-child-contract', function(event) {
		$.suredy.showModal({
			size : 'lg',
			title : '新建子合同',
			showFoot : false,
			uri : $.suredy.contextPath + '/contract/form/child?projId=' + $('input.project-id').val()
		});
	});

	// 删除子合同
	$('.children-contract-info').on('click', '.btn.delete-child-contract', function(event) {
		if (!window.confirm("确定删除合同信息？")) {
			return false;
		}

		var $this = $(this);
		var id = $this.data('id');

		if (!id) {
			alert('未知的合同信息');
			return false;
		}

		$.ajax({
			url : $.suredy.contextPath + '/contract/form/delete',
			type : 'post',
			traditional : true,
			data : {
				id : id
			},
			success : function(success, textStatus, jqXHR) {
				if (!success) {
					alert('删除操作失败！');
					return false;
				}

				var listUri = $.suredy.contextPath + '/contract/list/children-contract-list/' + $('input.project-id').val();

				$.suredy.loadContent(listUri, '.tab-pane.children-contract-info');
			},
			error : function(jqXHR, textStatus, errorThrown) {
				alert('删除操作失败！\n' + errorThrown);
			}
		});
	});

	// 编辑子合同付款信息
	$('html').on('click', '.edit-children-pay', function() {
		var $this = $(this);
		$.suredy.showModal({
			size : 'lg',
			title : '付款信息',
			showFoot : false,
			uri : $.suredy.contextPath + '/payment/list/children-contract-pay-list/' + $this.data('contract-id')
		});
	});

	// 禁止表单回车提交
	$('html').on('keydown', '.form-data form', function(event) {
		if (event.keyCode == 13) {
			return false;
		}
	});

	// 合同签订情况变更事件
	$('.form-data .show-data.editable').on('project.contracted', function(event) {
		var $this = $(this);

		if ($('.data', $this).text() === '已签订') {
			$('.nav-tabs li.contract').removeClass('hide');
			$('div.contract-info').removeClass('hide');
		} else {
			$('.nav-tabs li.contract').addClass('hide');
			$('div.contract-info').addClass('hide');
		}
	});

	// edit field
	$('html').on('click', '.form-data .show-data.editable', function(event) {
		var showData = $(this);
		var editData = $('+.edit-data', showData);

		// 取消所有显示效果
		$('.form-data .show-data').removeClass('hide');
		$('.form-data .edit-data').addClass('hide');

		showData.addClass('hide');
		editData.removeClass('hide');

		$('.data', editData).focus();
		$('.data.datetimepicker', editData).click();
	});

	// submit field data
	$('html').on('click', '.form-data .edit-data .icon-ok', function(event) {
		var $this = $(this);
		var formData = $this.parents('.form-data');
		var form = $('form', formData);

		form.ajaxSubmit({
			success : function(success, textStatus, jqXHR) {
				if (!success) {
					alert('修改失败！');
					return false;
				}

				var showData = $('.show-data', formData);
				var editData = $('.edit-data', formData);

				var val;
				if ($('.data', editData).get(0).tagName === 'SELECT')
					val = $('.data option:selected', editData).text();
				else
					val = $('.data', editData).val();

				$('.data', showData).text(val || (showData.data('empty-str') || '-'));

				// 触发事件
				if (showData.data('event')) {
					showData.trigger(showData.data('event'));
				}

				$('.form-data .show-data').removeClass('hide');
				$('.form-data .edit-data').addClass('hide');
			},
			error : function(jqXHR, textStatus, errorThrown) {
				alert('修改失败！\n' + errorThrown);
			}
		});
	});

	// cancel edit field data
	$('html').on('click', '.form-data .edit-data .icon-remove', function(event) {
		var $this = $(this);
		var formData = $this.parents('.form-data');
		var form = $('form', formData);

		if (form.length > 0)
			form[0].reset();

		$('.form-data .show-data').removeClass('hide');
		$('.form-data .edit-data').addClass('hide');
	});

	// 初始化费用支出列表
	$.suredy.init_cost_list = function() {
		var costList = $('table.cost-list');
		var btns = [];

		// update
		if (costList.hasClass('update')) {
			btns[btns.length] = {
				text : '编辑',
				icon : 'icon-pencil',
				style : 'btn-primary btn-sm cost-edit-btn',
				click : function(page, pageSize, key) {
					if ($(this).attr('disabled') === 'disabled')
						return false;

					var checked = $.suredy.list.checked(costList);

					if (checked.length !== 1) {
						alert('只能选择一条信息进行编辑！');
						return false;
					}

					var id = checked.data('id');
					var projId = $('input.project-id').val();
					var uri = $.suredy.contextPath + '/cost/form?id=' + id + '&projId=' + projId;

					$.suredy.showModal({
						title : '修改费用支出',
						showFoot : false,
						uri : uri
					});

				}
			};
		}

		// create
		if (costList.hasClass('create')) {
			btns[btns.length] = {
				text : '添加',
				icon : 'icon-plus',
				style : 'btn-warning btn-sm',
				click : function(page, pageSize, key) {
					var projId = $('input.project-id').val();
					var uri = $.suredy.contextPath + '/cost/form?projId=' + projId;

					$.suredy.showModal({
						title : '增加费用支出',
						showFoot : false,
						uri : uri
					});
				}
			};
		}

		// delete
		if (costList.hasClass('delete')) {
			btns[btns.length] = {
				text : '删除',
				icon : 'icon-trash',
				style : 'btn-danger btn-sm',
				click : function(page, pageSize, key) {
					var checked = $.suredy.list.checked(costList);

					if (checked.length === 0) {
						return false;
					}

					if (!window.confirm('确定删除[' + checked.length + ']条费用支出记录么？'))
						return false;

					var id = [];
					checked.each(function(i) {
						id[i] = $(this).data('id');
					});

					var uri = $.suredy.contextPath + '/cost/list/delete';

					$.ajax({
						url : uri,
						type : 'post',
						traditional : true,
						data : {
							id : id
						},
						success : function(success, textStatus, jqXHR) {
							if (!success) {
								alert('删除操作失败！');
								return false;
							}

							var listUri = $.suredy.contextPath + '/cost/list/' + $('input.project-id').val();

							$.suredy.loadContent(listUri, '.tab-pane.cost-info', function() {
								// 重绘列表
								$.suredy.init_cost_list();
							});
						},
						error : function(jqXHR, textStatus, errorThrown) {
							alert('删除操作失败！\n' + errorThrown);
						}
					});

				}
			};
		}

		costList.list({
			footer : false,
			checkbox : costList.hasClass('update') || costList.hasClass('delete'),
			searchDefaultText : '输入[支付名称]进行查询',
			searchValue : costList.data('key') || false,
			paginate : function(page, pageSize, key) {
				var listUri = $.suredy.contextPath + '/cost/list/' + $('input.project-id').val();

				$.suredy.loadContent(listUri, '.tab-pane.cost-info', {
					key : key
				}, function() {
					// 重绘列表
					$.suredy.init_cost_list();
				});
			},
			btns : btns
		});

		// 禁用编辑按钮
		$('.cost-edit-btn').attr('disabled', 'disabled');

		costList.on('click', function() {
			var checked = $.suredy.list.checked($(this));

			if (checked.length !== 1) {
				$('.cost-edit-btn').attr('disabled', 'disabled');
			} else {
				$('.cost-edit-btn').removeAttr('disabled');
			}
		});
	};

	// 初始化收款信息列表
	$.suredy.init_pay_list = function() {
		var payList = $('table.pay-list');
		var btns = [];

		// update
		if (payList.hasClass('update')) {
			btns[btns.length] = {
				text : '编辑',
				icon : 'icon-pencil',
				style : 'btn-primary btn-sm pay-edit-btn',
				click : function(page, pageSize, key) {
					if ($(this).attr('disabled') === 'disabled')
						return false;

					var checked = $.suredy.list.checked(payList);

					if (checked.length !== 1) {
						alert('只能选择一条信息进行编辑！');
						return false;
					}

					var id = checked.data('id');
					var cid = $('input.contract-id').val();
					var uri = $.suredy.contextPath + '/payment/form?id=' + id + '&contractId=' + cid;

					$.suredy.showModal({
						title : '修改收款信息',
						showFoot : false,
						uri : uri
					});

				}
			};
		}

		// create
		if (payList.hasClass('create')) {
			btns[btns.length] = {
				text : '添加',
				icon : 'icon-plus',
				style : 'btn-warning btn-sm',
				click : function(page, pageSize, key) {
					var cid = $('input.contract-id').val();
					var uri = $.suredy.contextPath + '/payment/form?contractId=' + cid;

					$.suredy.showModal({
						title : '增加收款信息',
						showFoot : false,
						uri : uri
					});
				}
			};
		}

		// delete
		if (payList.hasClass('delete')) {
			btns[btns.length] = {
				text : '删除',
				icon : 'icon-trash',
				style : 'btn-danger btn-sm',
				click : function(page, pageSize, key) {
					var checked = $.suredy.list.checked(payList);

					if (checked.length === 0) {
						return false;
					}

					if (!window.confirm('确定删除[' + checked.length + ']条收款信息？'))
						return false;

					var id = [];
					checked.each(function(i) {
						id[i] = $(this).data('id');
					});

					var uri = $.suredy.contextPath + '/payment/list/delete';

					$.ajax({
						url : uri,
						type : 'post',
						traditional : true,
						data : {
							id : id
						},
						success : function(success, textStatus, jqXHR) {
							if (!success) {
								alert('删除操作失败！');
								return false;
							}

							var listUri = $.suredy.contextPath + '/payment/list/' + $('input.contract-id').val();

							$.suredy.loadContent(listUri, '.pay-info', function() {
								// 重绘列表
								$.suredy.init_pay_list();
							});
						},
						error : function(jqXHR, textStatus, errorThrown) {
							alert('删除操作失败！\n' + errorThrown);
						}
					});

				}
			};
		}

		payList.list({
			header : btns.length > 0,
			footer : false,
			checkbox : payList.hasClass('update') || payList.hasClass('delete'),
			search : false,
			searchValue : payList.data('key') || false,
			btns : btns
		});

		// 禁用编辑按钮
		$('.pay-edit-btn').attr('disabled', 'disabled');

		payList.on('click', function() {
			var checked = $.suredy.list.checked($(this));

			if (checked.length !== 1) {
				$('.pay-edit-btn').attr('disabled', 'disabled');
			} else {
				$('.pay-edit-btn').removeAttr('disabled');
			}
		});
	};

	$.suredy.init_cost_list();
	$.suredy.init_pay_list();

	// 初始化选中的项目成员
	var initProjMember = function() {
		var tree = $('.project-member-tree');
		var memberId = [];
		var node = $('li>a', tree);
		var contains = function(id) {
			for ( var i = 0; i < memberId.length; i++) {
				if (id === memberId[i])
					return true;
			}

			return false;
		};

		$('.member input.member-id').each(function(i) {
			memberId[i] = $(this).val();
		});

		node.each(function(i) {
			var $this = $(this);
			var data = $.suredy.tree.data($this);
			var checkbox = $('.tree-checkbox', $this);

			if (contains(data.id)) {
				// 选中
				if (!checkbox.hasClass('node-checked'))
					$('.tree-checkbox', $this).click();
			} else {
				if (checkbox.hasClass('node-checked'))
					$('.tree-checkbox', $this).click();
			}
		});
	};

	// 初始化选人控件
	$('.project-member-tree').tree($.suredy.contextPath + '/config/ou/tree/false/true/true', {
		checkbox : true,
		onlyLeafCheckbox : true,
		style : 'department',
		showTitle : true
	});

	// 初始化选中的项目成员
	initProjMember();

	// 编辑项目成员
	$('.form-data .edit-data .icon-ok.edit-proj-member').on('click', function(event) {
		var $this = $(this);
		var formData = $this.parents('.form-data');
		var showData = $('.show-data', formData);
		var tree = $('.project-member-tree', formData);
		var data = $($.suredy.tree.data($.suredy.tree.checked(tree)));
		var projId = $this.data('proj-id');
		var userIds = [];

		data.each(function(i) {
			userIds[i] = this.id;
		});

		$.ajax({
			url : $.suredy.contextPath + '/project/form/edit-members',
			type : 'post',
			traditional : true,
			data : {
				projId : projId,
				userIds : userIds
			},
			success : function(success, textStatus, jqXHR) {
				if (!success) {
					alert('修改成员失败！');
					return false;
				}

				if (data.length > 0) {
					showData.html('');

					data.each(function(i) {
						var html = '<div class="member">\
										<input type="hidden" class="member-id" value="' + this.id + '">\
										<span class="data">' + this.name + '</span>\
									</div>';
						showData.append(html);
					});
				} else {
					showData.html('<br>&lt;暂无&gt;');
				}

				$('.form-data .show-data').removeClass('hide');
				$('.form-data .edit-data').addClass('hide');
			},
			error : function(jqXHR, textStatus, errorThrown) {
				alert('修改失败！\n' + errorThrown);
			}
		});

		return false;
	});

	// 取消编辑项目成员
	$('.form-data .edit-data .icon-remove.cancel-edit-proj-member').on('click', function(event) {
		initProjMember();
		$('.form-data .show-data').removeClass('hide');
		$('.form-data .edit-data').addClass('hide');
		return false;
	});

	// 费用支出状态切换
	$('html').on('change', '.payed-status', function() {
		var $this = $(this);
		var status = eval($this.val());

		var id = $this.parents('tr').data('id');

		if (!id) {
			alert('操作失败');
			return false;
		}

		$.ajax({
			url : $.suredy.contextPath + '/cost/form/update-status',
			data : {
				id : id,
				status : status
			},
			type : 'POST',
			dataType : 'json',
			success : function(success, textStatus, jqXHR) {
				if (!success) {
					$('option', $this).removeAttr('selected');
					if (status)
						$('option.not-payed', $this).attr('selected', true);
					else
						$('option.payed', $this).attr('selected', true);

					alert('操作失败！');
					return false;
				}

				if (status) {
					$this.removeClass('bg-danger text-danger');
				} else {
					$this.addClass('bg-danger text-danger');
				}
			},
			error : function(jqXHR, textStatus, errorThrown) {
				$('option', $this).removeAttr('selected');
				if (status)
					$('option.not-payed', $this).attr('selected', true);
				else
					$('option.payed', $this).attr('selected', true);

				alert('操作失败！\n' + errorThrown);
			}
		});
	});
});